<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>02-控制最大请求数-任务数</title>
	</head>

	<body>
		<script>
			// TODO 方式一，控制请求url
			const urls = [];
			for (let i = 1; i <= 10; i++) {
				urls.push('https://jsonplaceholder.typicode.com/todos/' + i);
			}
			// 02-控制最大请求数-任务数-可获取返回值
			function controlRequest(urls, maxNum = 20) {
				return new Promise((resolve, rej) => {
					const result = [];
					let index = 0;
					let count = 0;
					async function request() {
						if (index === urls.length) return;
						const i = index;
						const url = urls[index];
						index++;
						fetch(url)
							.then(res => res.json())
							.then(res => {
								result[i] = res;
							})
							.catch(err => {
								result[i] = err;
							})
							.finally(() => {
								request();
								count++;
								if (count === urls.length) {
									resolve(result);
								}
							});
					}

					// 同时执行最多任务数
					const min = Math.min(maxNum, urls.length);
					for (let i = 0; i < min; i++) {
						request();
					}
				});
			}

			// controlRequest(urls, 2).then((res) => {
			// 	console.log(res);
			// });
		</script>

		<script>
			// TODO 方式二，控制请求实例
			const requestList = [];
			for (let i = 1; i <= 10; i++) {
				function http() {
					return fetch('https://jsonplaceholder.typicode.com/todos/' + i);
				}
				requestList.push(http);
			}

			function controlRequest2(https, maxNum = 20) {
				return new Promise((resolve, rej) => {
					const result = []; // 返回结果集
					let index = 0; // 当前执行任务的最大索引
					let count = 0; // 执行完成数量
					async function request() {
						if (index === https.length) return;
						const i = index;
						const http = https[index];
						index++;
						http()
							.then(res => res.json())
							.then(res => {
								result[i] = res;
							})
							.catch(err => {
								result[i] = err;
							})
							.finally(() => {
								request();
								count++;
								if (count === https.length) {
									resolve(result);
								}
							});
					}

					// 同时执行最多任务数
					const min = Math.min(maxNum, https.length);
					for (let i = 0; i < min; i++) {
						request();
					}
				});
			}

			controlRequest2(requestList, 2).then(res => {
				console.log(res);
			});
		</script>
	</body>
</html>
